<template>
<div >
  <el-row>
    <el-col :span="24">
      <Title></Title>
    </el-col>
  </el-row>

  <el-row style="margin-top: 70px">
    <el-col :span="24"> <div>


      <el-row  :gutter="10">
        <el-col :span="4">
          <el-upload
              ref="upload"
              action="https://jsonplaceholder.typicode.com/posts/"
              class="upload-demo"
              accept="xls,xlsx"
              :show-file-list="false"
              :auto-upload="false"
              :multiple="false"
              :on-change="fileOnChange">
            <el-button slot="trigger" size="small" type="primary"  icon="el-icon-plus">处方导入</el-button>

          </el-upload>
        </el-col>
        <el-col :span="2"  style="margin-top: 7px "><div class="medicineLabel" >药物数：</div></el-col>

        <el-col :span="3">

          <el-select  v-model="medcineValue" placeholder="请输入药对数" style="width: 130px">
            <el-option
                v-for="item in medicineOptions"
                :key="item.medcineValue"
                :label="item.medcineLabel"
                :value="item.medcineValue">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4" style="margin-top: 7px;margin-left:40px;padding-left: 30px;">
          <div class="sortLabel">
            <span>排序药物个数：</span>
          </div>
        </el-col>
        <el-col :span="4"><div class="grid-content bg-purple-light">  <el-select v-model="sortValue" placeholder="降序N个排序显示">
          <el-option
              v-for="item in sortOptions"
              :key="item.sortValue"
              :label="item.sortLabel"
              :value="item.sortValue">
          </el-option>
        </el-select></div></el-col>

        <el-col :span="6" style=";padding-left: 40px" >
          <el-button type="primary" @click="sendJsonData_to_backend">确定</el-button>
          <el-button
              style="margin-left: 20px"
              type="primary"
              >
            <download-excel class="export-excel-wrapper" :data="tableData" :fields="json_fields" name="">
            </download-excel>
          </el-button>
        </el-col>
      </el-row>
      <div class="fengexian"></div>
    </div></el-col>
  </el-row>
  <el-row style="margin: 30px" >
<!--    //echart频度可视化表格-->
    <el-col :span="14"    >
      <div id="echartsDiv" style="width: 600px;height: 400px"></div>
    </el-col>
<!--    表格表示-->
    <el-col :span="10" style="background: #da0758">
      <div class="tableDiv" >
      <!--  :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"-->
      <el-table
          :show-header="tableFlag"
          stripe="true"
          border="true"
          highlight-current-row="true"
          :data="tableData"
          size="medium"
         >
        <el-table-column
            prop="id"
            label="编号"
            width="112">
        </el-table-column>
        <el-table-column
            prop="resultMedicne"
            label="药物"
            width="180">
        </el-table-column>
        <el-table-column
            prop="sortNum"
            label="频次"
            width="150">
        </el-table-column>
      </el-table>
    </div></el-col>
  </el-row>

  <el-row><FooterTitle></FooterTitle></el-row>
</div>
</template>

<script>
import FooterTitle from "../../components/FooterTitle";
import FreInput from "./FreInput";
import EchartsDiv from "./EchartsDiv";
import TableDiv from "./TableDiv";
import Import from "../Tools/Import";
import Title from "../../components/Title";
var XLSX = require("xlsx");
export default {
  name: "FrequencyAnalysis",
components:{
  FooterTitle,
  FreInput,
  TableDiv,
  EchartsDiv,
  Import,
  Title
},
  //加载echarts
  mounted() {
    this.drawLine();
  },
  data(){
    return{
      medicineOptions: [{
        medcineValue: '1',
        medcineLabel: '单味药'
      }, {
        medcineValue: '2',
        medcineLabel: '药对'
      }, {
        medcineValue: '3',
        medcineLabel: '三元组'
      }],
      medcineValue: [],
//--------------------------------------------------------------------------------------------------
      sortOptions:[
        {
          sortValue:'1',
          sortLabel:'1'
        },
        {
          sortValue:'2',
          sortLabel:'2'
        },
        {
          sortValue:'3',
          sortLabel:'3'
        },
        {
          sortValue:'4',
          sortLabel:'4'
        },
        {
          sortValue:'5',
          sortLabel:'5'
        },
        {
          sortValue:'6',
          sortLabel:'6'
        },
        {
          sortValue:'7',
          sortLabel:'7'
        },
        {
          sortValue:'8',
          sortLabel:'8'
        },
        {
          sortValue:'9',
          sortLabel:'9'
        },
        {
          sortValue:'10',
          sortLabel:'10'
        },
      ],
      sortValue:[],
      excel_json:"",
      fre_data_form:{
        med_num:this.med_num,//单味药，药对，三味药
        sort_num:this.sort_num,
        json:'',
      },

      // this.$store.state.frequencyReturnData
      tableData: Array,
      search: '',
      //echart的div
      EchartColum:'',
      //存药物以及药物频度
      sortNumArr:[],
      MedicineResultArr:[],
      //设置echarts的参数
      option:{
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            "axisLabel":{     //加上这个强制显示
              interval: 0,
              rotate:-50,//-30度角倾斜显示
              margin: 5
            }
          },
          {
            type: 'category',
            data: [],
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '药物名:',
            type: 'bar',
            barWidth: '60%',
            data: [],
          }
        ],
        toolbox: {

          feature: {
            mark:{show:true},
            saveAsImage: {
              show: true,
              pixelRatio:1,
              title:"下载",
              type:'png',
              lang:['点击保存'],
              name:"频度分析可视化图表"
            }
          }
        }


      },
      // 下载相关的json_fields
      json_fields: {
        "编号": "id", //常规字段
        "药物":"resultMedicne",
        "频度":"sortNum"
      },
      //控制表头是否显示（有数据时候数据显示，无数据不显示）
      tableFlag:false

    }

  },
  methods:{
    fileOnChange(file, fileList){
      let files = {0:file.raw}
      this.readExcel1(files);
    },
    readExcel1(files) {//表格导入
      var that = this;
      if(files.length<=0){//如果没有文件名
        return false;
      }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){

        this.$message.error('上传格式不正确，请上传xls或者xlsx格式');
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: 'binary'
          });

          const wsname1 = workbook.SheetNames[0];//取第一张表
          console.log(wsname1)
          const ws1 = XLSX.utils.sheet_to_json(workbook.Sheets[wsname1]);//生成第一张表的json表格内容
          console.log(ws1.length)
          var medicineArray = new Array();
          for(var i=0;i<ws1.length;i++){
            medicineArray.push(ws1[i].处方)
          }

          //console.log(medicineArray)

          this.excel_json = medicineArray;
          console.log(this.excel_json);
          console.log(typeof (this.excel_json))
          //当我点击确定按钮的时候提交数据
          // this.sendJsonData_to_backend()
          try{
          }catch(err){
            console.log(err)
          }
          this.$refs.upload.value = '';
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },

    //将 -----药对，排序个数，excel表json数据传给后端处理
    sendJsonData_to_backend(){
      //对数据进行校验
      this.checkInput(this.excel_json,this.medcineValue,this.sortValue);


    },
    //下载频次分析数据
    downloadFreq(){
      this.$notify({
        title: '成功',
        message: '这是一条成功的提示消息',
        type: 'success'
      });
    },
    //初始化表格
    initChartDiagram(){
      this.option.xAxis[0].data = JSON.parse(JSON.stringify(this.MedicineResultArr  ));
      this.option.series[0].data = JSON.parse(JSON.stringify(this.sortNumArr));
      this.EchartColum = this.$echarts.init(document.getElementById("echartsDiv"));
      this.EchartColum.setOption(this.option)
    },
    //将后端的数据处理成ehcart能够识别的模式
    ChangeEchartsData(){
      let len = this.sortValue;
      //处理频度
      var sortNumArr = new Array(len);
      for(let i=0.;i<len;i++){
        sortNumArr[i] = this.tableData[i].sortNum;
      }
      this.sortNumArr = sortNumArr ;
      //处理药物
     var MedicineResultArr = new Array(len);
      for(let i=0.;i<len;i++){
        MedicineResultArr[i] = this.tableData[i].resultMedicne;
        console.log( MedicineResultArr[i])
      }
      this.MedicineResultArr = MedicineResultArr;

    },
    //点击确定按钮
    sumbitBtn(){
      let that = this

      this.$axios.post('http://localhost:8800/freanalysis', {
        med_num:that.medcineValue,
        sort_num:that.sortValue,
        json:that.excel_json,
      })
          .then(function(response) {
            console.log("-------------")
            that.tableData = JSON.parse(JSON.stringify(response.data)),
            that.ChangeEchartsData()
            //展示数据
            that.initChartDiagram()
            that.tableFlag=true
          }).catch(function(error) {
        console.log("error")
      })
    },
    //对输入的参数进行校验
    checkInput(excel_json,med_num,sort_num){
      console.log(excel_json)
      //如果没有传入处方的
      if(excel_json.length==0){
        this.$message({
          message: '请传入excel处方',
          center: true,
          type: 'error'
        });
      }
      //药对信息
      else if(med_num.length==0){
        this.$message({
          message: '请传入药对信息',
          center: true,
          type: 'error'
        });
      }
      //排序的个数校验
      else if(sort_num.length==0){
        this.$message({
          message: '请传入排序的个数',
          center: true,
          type: 'error'
        });
      }
      else{
        this.sumbitBtn();
      }
    }
  }
}
</script>

<style scoped>

.fengexian{
  position: relative;
  margin: 15px ;
  width:100%;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);

}
</style>
